<?php
class ApiPostArticle extends API {

	function __construct()
	{
		parent::__construct();
		$this->loadFunctionOutSite();
		$this->run();
	}

	public function home()
	{
		global $wp_query;
		if(isset($_GET['id']) && (int)$_GET['id'] > 0){
			$data = $this->queryPosts(array('posts_per_page'=>15,'paged'=>$_GET['id']));
			$pagination = $this->getPaginationURL(array(
				'method'=>__METHOD__,
				'id'=>$_GET['id'],
				'last'=>$wp_query->max_num_pages,
			));
			return array_merge($pagination,$data);
		}else{
			$this->responseData(500,array('error'=>true,'message'=>'Parameter id is missing'));
		}
	}

	public function run()
	{
		$data = $this->get();
		if(!empty($data['data'])){
			$this->responseData(200,array_merge(array('error'=>$data['error']),$data['data']));
		}
	}

	public function get()
	{
		$call = $this->getMethod($_GET);
		return $this->validateMethod(array(
			'class'=>$call['class'],
			'currentClass'=>__CLASS__,
			'action'=>$call['action'],
			'data'=>$this->$call['action'](isset($call['id']) ? $call['id'] : null)
		));
	}

	/* Functions support for API Post */

	public function getCategories($id,$post)
	{
		global $wp_rewrite;
		$categories = array();
		$cats = get_the_category($id);
		foreach($cats as $category){
			$categories[] = array(
				'id'=>$category->term_id,
				'name'=>$category->cat_name,
				'link'=>get_category_link($category->term_id)
			);
		}
		return $categories;
	}

	public function queryPosts($query)
	{
		global $wp_query;
		$data = array();
		$getPosts = query_posts($query);
		if(!empty($getPosts)){
			foreach($getPosts as $post) {
				setup_postdata($post);
				$data[] = array(
					'id'=>$post->ID,
					'author'=>array('id'=>get_the_author_meta('ID'),'name'=>get_the_author_meta('display_name'),'link'=>get_author_posts_url(get_the_author_meta('ID'))),
					'date'=>$post->post_date,
					'title'=>$post->post_title,
					'contents'=>htmlspecialchars(str_replace("[&hellip;]","",apply_filters('the_excerpt', get_the_excerpt()))),
					'thumbnail'=>get_post_meta($post->ID, 'thumbnail', true),
					'status'=>$post->post_status,
					'slug'=>$post->post_name,
					'date_modified'=>$post->post_modified,
					'permalink'=>get_permalink($post->ID),
					'type'=>$post->post_type,
					'comments'=>$post->comment_count,
					'categories'=>$this->getCategories($post->ID,$post),
				);
			}
			wp_reset_postdata();
			return array('number_pages'=>$wp_query->max_num_pages,'posts'=>$data);
		}else{
			$this->responseData(200,array('error'=>true,'message'=>'No items where found for API'));
		}
	}

	/* End Functions */

}